<script setup lang="ts">
  import {
    ref,
    defineProps,
    defineEmits,
    computed,
    watch,
    onMounted,
    nextTick,
  } from 'vue';
  import { useBooleanStore } from '@/store';
  import { getUserJob } from '@/utils/auth';
  import { Notification } from '@arco-design/web-vue';
  import {
    searchByBarcode,
    partWorkbinOutStoreroom,
  } from '@/api/material-receipt';

  const props = defineProps<{
    localTableData: any;
  }>();

  const emit = defineEmits(['updateArray']);
  const booleanStore = useBooleanStore();
  const hStyle = ref({
    'background-color': booleanStore.color,
    'border-radius': booleanStore.borderRadius,
  });
  const scanInput = ref<any>('');
  const pageSize = ref<number>(5);
  const pageNumber = ref<number>(1);
  const current = ref<number>(1);
  const disabled = ref<boolean>(false);
  const scanCode = ref<string>('');
  const scanCodeType = ref<string>('Y');
  // 操作码俩次确认
  const isConfirm = ref<boolean>(false);
  // 存储移交成功的数据
  const scanDataList = ref<any[]>([]);
  const inputTableData = ref<any[]>([]);

  function resetCode() {
    scanDataList.value = [];
    scanCode.value = '';
  }

  // 零件扫码移交
  async function topToLastScan() {
    try {
      const info = ref({
        barCode: computed(() => scanCode.value),
        sendType: scanCodeType.value,
        pageParameter: computed(() => ({
          rows: 500,
          page: 1,
        })),
      });
      disabled.value = true;
      const data: any = await searchByBarcode(info.value);
      if (data.retCode === '200') {
        for (let i = 0; i < data.responseBody.result.length; i += 1) {
          scanDataList.value.push(data.responseBody.result[i]);
        }
        Notification.success({
          title: '成功',
          content: data.message,
          closable: true,
        });
        nextTick(() => {
          scanInput.value.focus();
        });
      } else {
        Notification.error({
          title: '失败',
          content: data.message,
          closable: true,
        });
      }
    } catch (error) {
      Notification.error({
        title: '失败',
        content: '移交失败',
        closable: true,
      });
      console.log(error);
    } finally {
      scanCode.value = '';
      nextTick(() => {
        scanInput.value.focus();
      });
      disabled.value = false;
    }
  }
  const getUserJobNumber = ref<any>(getUserJob());
  // 扫码移交加输入框回车
  async function scanSubmit() {
    // 判空
    if (!scanCode.value) {
      return;
    }
    if (scanCode.value === '9005' || scanCode.value === '90059005') {
      if (scanDataList.value.length > 0) {
        if (isConfirm.value) {
          const info: any = ref({
            data: booleanStore.listTwo[0],
            receiveEmpCode: getUserJobNumber.value,
          });
          disabled.value = true;
          booleanStore.toggleBool(0);
          try {
            const data: any = await partWorkbinOutStoreroom(info.value);
            if (data.retCode === '200') {
              Notification.success({
                title: '成功',
                content: data.message,
                closable: true,
              });
              scanDataList.value = [];
              emit('updateArray');
            } else {
              Notification.error({
                title: '失败',
                content: data.message,
                closable: true,
              });
            }
          } catch (error) {
            Notification.error({
              title: '失败',
              content: '网络异常',
              closable: true,
            });
            console.log(error);
          } finally {
            booleanStore.toggleBool(0);
            disabled.value = false;
            scanCode.value = '';
            nextTick(() => {
              scanInput.value.focus();
            });
            isConfirm.value = false;
          }
        } else {
          // setTimeout(() => {
          //   scanCode.value = '';
          // }, 600);
          isConfirm.value = true;
        }
      } else {
        Notification.warning({
          title: '提示',
          content: '请先扫零件编码',
          closable: true,
        });
      }
    } else {
      const inputData = inputTableData.value.find(
        (item: any) => item.barcode === scanCode.value
      );
      if (inputData && inputData.sealDate !== null) {
        const currentDate = new Date(); // 获取当前时间的时间戳
        const sealDateObj = new Date(inputData.sealDate); // 将油封为时间戳
        const diffTime = currentDate.getTime() - sealDateObj.getTime(); // 计算时间差（毫秒）
        const diffDays = diffTime / (1000 * 60 * 60 * 24); // 转换为天数
        if (diffDays > 0) {
          Notification.error({
            title: '提示',
            content: `图号${inputData.itemCode}油封期已超期`,
            closable: true,
          });
        } else if (diffDays > -90 && diffDays <= 0) {
          Notification.error({
            title: '提示',
            content: `图号${inputData.itemCode}油封期已临期`,
            closable: true,
          });
        }
      }

      for (let i = 0; i < scanDataList.value.length; i += 1) {
        if (scanDataList.value[i]?.barcode === scanCode.value) {
          Notification.warning({
            title: '提示',
            content: '请误重复扫码',
            closable: true,
          });
          scanCode.value = '';
          return;
        }
      }
      await topToLastScan();
    }
  }

  onMounted(() => {
    nextTick(() => {
      scanInput.value.focus();
    });
  });
  // 监听分页;
  // watch([() => booleanStore.pageNum, () => booleanStore.pageSize], () => {
  //   if (booleanStore.num5 === 4) {
  //     pageNumber.value = booleanStore.pageNum;
  //     pageSize.value = booleanStore.pageSize;
  //     handleSearch();
  //   }
  // });
  // watch(
  //   () => booleanStore.update,
  //   () => {
  //     if (booleanStore.num6 === 2) handleSearch();
  //   }
  // );
  watch(
    () => props.localTableData,
    () => {
      inputTableData.value = props.localTableData || [];
    },
    { immediate: true }
  );
  watch(
    scanDataList,
    () => {
      if (scanDataList.value.length !== 0) {
        current.value = 2;
      } else {
        current.value = 1;
      }
      booleanStore.setList(scanDataList.value, 6);
    },
    { deep: true }
  );
</script>

<template>
  <!-- <a-card :header-style="hStyle">
    <template #title>
      <div class="font">流程进度</div>
    </template>
    <a-steps type="arrow" small changeable :current="current">
      <a-step :description="description">扫码移交</a-step>
      <a-step :description="description2">零件接收</a-step>
    </a-steps>
  </a-card> -->
  <a-card :header-style="hStyle" :bordered="false">
    <template #title>
      <div class="font">扫码操作</div>
    </template>
    <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col :span="6">
        <div>
          <a-input
            ref="scanInput"
            v-model="scanCode"
            placeholder="请输入缓存箱/托盘码/条码"
            size="large"
            :disabled="disabled"
            @keyup.enter="scanSubmit"
          />
        </div>
      </a-col>
      <a-col :span="6">
        <a-button type="primary" size="large" @click="scanSubmit"
          >零件接收</a-button
        >
        <a-button class="btn-reset" size="large" @click="resetCode"
          >重置</a-button
        >
      </a-col>
      <a-col :span="6">
        <a-select v-model="scanCodeType" size="large">
          <a-option value="Y">直配</a-option>
          <a-option value="N">不直配</a-option>
        </a-select>
      </a-col>
      <a-col :span="6">
        <div class="div-tips"
          >默认物料需要直配的话去其他界面操作，如果不直配要入库，请选择不直配</div
        >
      </a-col>
    </a-row>
  </a-card>
</template>

<style scoped>
  .margin-top {
    margin-top: 10px;
  }
  .btn-group {
    float: right;
    margin-top: 15px;
  }

  .btn-reset {
    margin-left: 10px;
  }
  .font {
    font-size: 20px;
    color: black;
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI',
      Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue',
      sans-serif;
  }
  .div-tips {
    align-items: center;
    text-align: center;
    color: #999;
  }
</style>
